import json
from django.shortcuts import render, reverse, redirect
from django.http.response import HttpResponse, JsonResponse

# Create your views here.


def session_demo(request):
    # 设置session  用请求对象
    request.session['name'] = 'yanna'
    # 读取session
    print(request.session.get('name'))
    return HttpResponse("session_demo")


def cookie_demo(request):
    # 设置cookie

    response = HttpResponse('cookie_demo')
    # 设置cookie
    response.set_cookie('name', 'cd', max_age=3600)
    # 读取cookie
    print(request.COOKIES.get('name'))
    return response


def redirect_demo(request):
    """演示重定向"""
    # 命名空间的作用就是指定反向解析查找的范围，防止其他子应用出现别名相同出现解析错误的问题
    print(reverse('request_response:redirect_demo'))
    # 重定向的时候一定要在路由前面加上跟路由/ 不然就是表示 在原有路由后面追加users/index/
    # return redirect('/users/index/')
    # 反向解析出来自己就能加上跟路径
    return redirect(reverse('users:index'))

    # return HttpResponse('hello')


def response_demo(request):
    # HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
    return HttpResponse(content='晏娜'.encode(encoding='gbk'), content_type='text/plain', status=201)


def json_response(request):
    """演示响应json数据"""
    json_dict = {
        "name": "cd",
        "age": 20
    }
    return JsonResponse(json_dict)


def get_request_head(request):
    print(request.META['CONTENT_TYPE'])
    print(request.user)
    return HttpResponse('get_request_head')


def get_json(request):
    """获取请求体中的非表单数据"""
    json_str_byte = request.body
    json_str = json_str_byte.decode()
    dict1 = json.loads(json_str)
    print(dict1)
    return HttpResponse('get_json')


def get_form(request):
    """获取请求体中表单数据"""
    print(request.POST.get('like'))
    print(request.POST.getlist('like'))
    return HttpResponse('get_form')


def get_query_string(request):
    """获取查询字符串的数据"""
    # 注意这个GET不是GET请求  而是一个属性
    print(request.GET.get('a'))
    print(request.GET.getlist('a'))
    return HttpResponse('get_query_string')


# /weather/beijing/2018
def weather1(request, city, year):
    print(city)
    print(year)

    return HttpResponse('OK')